<?php

namespace My\Controller;

use Utuo\BackgroundController;
use Utuo\PHPExcel;

class MicroSeckillApplyController extends BackgroundController {
	private $microSeckillId;
	private $export=array(
		'0'=>'导出抢购成功信息',
		'1'=>'导出抢购失败信息',
		
	);
	public function _initialize() {
		$this->microSeckillId = I ( 'id' );
		$this->microSeckillId or $this->error ( 'id 丢失' );
		$this->setControllerTitle ( '微秒杀申请管理' );
		$this->setActionTitle ( array (
				'index' => '微秒杀申请列表',
				'recycle' => '回收站',
				'data' => '数据概况' 
		)
		, null, array (
				'id' => I ( 'id' ) 
		) );
		$this->setActionNav ( array (
				'index',
				'data',
				'recycle' 
		) );
	}
	public function getLists($is_deleted) {
		$exportOptions=\Utuo\Form::getOption($this->export,null,'导出全部信息');
		$microSeckill = M ( 'MicroSeckill' )->where ( 'status=1 and is_deleted=0' )->getField ( 'id,name' );
		$condation = array (
				'a.is_deleted' => $is_deleted,
				'a.cid' => $this->aid,
				'a.micro_seckill_id' => $this->microSeckillId 
		);
		$m = D ( "MicroSeckillApply a" );
		$microSeckillApply = $m->join ( '__MICRO_SECKILL__ m on a.micro_seckill_id=m.id' )->where ( $condation )->page ( $this->getPage (), $this->getPageSize () )->field ( 'a.*,m.name as microSeckillName' )->order ( 'a.id desc' )->select ();
		foreach ( $microSeckillApply as $k => &$v ) {
			$v ['statusOptions'] = \Utuo\Form::getOption ( D ( 'MicroSeckillApply' )->status, $v ['status'] );
			
		}
		$total = $m->join ( '__MICRO_SECKILL__ m on a.micro_seckill_id=m.id' )->where ( $condation )->count ();
		$this->showPage ( $total, $this->getPageSize () );
		$this->microSeckillApply = $microSeckillApply;
		$this->exportOptions=$exportOptions;
		$this->display ();
	}
	// 设置审核状态
	public function setStatusAction() {
		$id = I ( "id", 0, "intval" );
		$status = I ( "status", 0, "intval" );
		$d = D ( "MicroSeckillApply" );
		if ($d->where ( "id={$id}" )->setField ( "status", $status )) {
			$this->ajaxSuccess ();
		} else {
			$this->ajaxError ( $d->getError () );
		}
	}
	// 显示数据
	public function dataAction() {
		$m = M ( 'MicroSeckillApply' );
		$data = $m->field ( "micro_seckill_id,max(apply_time) as maxtime,min(apply_time) as mintime,count(micro_seckill_id) as num" )->group ( 'micro_seckill_id' )->where ( 'is_error=0' )->having ( 'micro_seckill_id=' . $this->microSeckillId )->select ();
		$partake = $m->field ( "micro_seckill_id,count(micro_seckill_id) as totalCount" )->group ( 'micro_seckill_id' )->having ( 'micro_seckill_id=' . $this->microSeckillId )->select ();
		foreach ( $data as &$v ) {
			foreach ( $partake as $p ) {
				$microSeckill = M ( 'MicroSeckill' )->where ( 'id=%d', $p ['micro_seckill_id'] )->find ();
				$v ['microSeckillName'] = $microSeckill ['name'];
				$v ['start_time'] = $microSeckill ['start_time'];
				$v ['end_time'] = $microSeckill ['end_time'];
				if ($v ['micro_seckill_id'] == $p ['micro_seckill_id']) {
					$v ['totalCount'] = $p ['totalCount'];
				}
			}
			$v ['time'] = $v ['maxtime'] - strtotime ( $v ['start_time'] );
			
			$hours = floor ( $v['time'] / 3600 );
			$minutes = floor(($v['time']-$hours*3600)/ 60 );
			$seconds = ($v['time']-$hours*3600) % 60;
			$v ['totalTime'] = $hours . "时" . $minutes . "分" . $seconds . "秒";
		}
		
		$this->assign ( "data", $data );
		$this->display ();
	}
	/**
	 * 导出Excel
	 */
	public function exportXLSAction() {
		$is_error = I ( 'is_error' );
		$data = $this->search ( $is_error);
		
		$objPHPExcel = new PHPExcel ();
		$objPHPExcel->getProperties ()->setCreator ( "微美风铃" )->setLastModifiedBy ( "微美风铃" )->setTitle ( "申请人员信息" )->setSubject ( "申请人员信息" )->setDescription ( "申请人员信息" )->setKeywords ( "申请人员信息" )->setCategory ( "申请人员信息" );
		
		/* 设置标题 */
		$titles = array (
				'ID',
				'所属微妙杀',
				'姓名',
				'电话',
				'地址',
				'申请时间',
				'抢购是否成功' 
		);
		$fields = array (
				'id' => array (
						'type' => 'number' 
				),
				'microSeckillName' => array (
						'type' => 'string' 
				),
				'name' => array (
						'type' => 'string' 
				),
				'tel' => array (
						'type' => 'string' 
				),
				'address' => array (
						'type' => 'string' 
				),
				'apply_time' => array (
						'type' => 'datetime',
						'format' => 'Y/m/d h:i:s' 
				),
				'is_error' => array (
						'type' => 'string' 
				) 
		);
		$sheet0 = $objPHPExcel->setActiveSheetIndex ( 0 );
		$rowNumber = 1;
		foreach ( $titles as $k => $v ) {
			$sheet0->setCellValue ( chr ( ord ( 'A' ) + $k ) . $rowNumber, $v );
		}
		$rowNumber ++;
		foreach ( $data as $v ) {
			$fieldIndex = 0;
			foreach ( $fields as $k0 => $v0 ) {
				$cellName = chr ( ord ( 'A' ) + $fieldIndex ++ ) . $rowNumber;
				$sheet0->setCellValueExplicit ( $cellName, $this->getShowData ( $v [$k0], $v0 ), $this->getCellFormat ( $v [$k0] ) );
				// $sheet0->setCellValue($cellName, );
			}
			$rowNumber ++;
		}
		$objPHPExcel->getActiveSheet ()->setTitle ( "申请人员信息" );
		header ( 'Content-Type: application/vnd.ms-excel' );
		header ( 'Content-Disposition: attachment;filename="' . date ( "Ymdhis" ) . '.xls"' );
		header ( 'Cache-Control: max-age=0' );
		header ( 'Cache-Control: max-age=1' ); // IE9时
		$objWriter = \PHPExcel_IOFactory::createWriter ( $objPHPExcel, 'Excel5' );
		$objWriter->save ( 'php://output' );
	}
	
	/**
	 * 获得单元格格式
	 * 
	 * @param unknown $fieldCfg        	
	 * @return string
	 */
	private function getCellFormat($fieldCfg) {
		if ($fieldCfg ['type'] == 'string') {
			return \PHPExcel_Cell_DataType::TYPE_STRING;
		} elseif ($fieldCfg ['type'] == 'money') {
			return \PHPExcel_Cell_DataType::TYPE_NUMERIC;
		}
		return \PHPExcel_Cell_DataType::TYPE_STRING;
	}
	
	/**
	 * 获得数据展示格式
	 * 
	 * @param unknown $value        	
	 * @param unknown $fieldCfg        	
	 * @return string unknown
	 */
	private function getShowData($value, $fieldCfg) {
		if ($fieldCfg ['type'] == 'datetime') {
			return date ( $fieldCfg ['format'], $value );
		}
		return $value;
	}
	private function search($is_error) {
		$condation = array (
				'a.is_deleted' => 0,
				'a.cid' => $this->aid 
		);
		$is_error>=0 and $condation ['is_error'] = $is_error;
		$m = D ( "MicroSeckillApply a" );
		$microSeckillApply = $m->join ( '__MICRO_SECKILL__ m on a.micro_seckill_id=m.id' )->where ( $condation )->field ( 'a.*,m.name as microSeckillName' )->order ( 'a.id desc' )->select ();
		
		foreach ( $microSeckillApply as &$v ) {
			$v ['is_error'] =$v['is_error']?'抢购未成功':'抢购成功';
		}
		
		return $microSeckillApply;
	}
}